<template>
  <div class="app-container">
    <!--查询区 -->
    <div class="filter-container">
      <el-row>
        <!-- 根据标题 -->
        <el-col :span="8">
          <el-input
            v-model="listQuery.title"
            placeholder="标题"
            class="filter-item"
            @keyup.enter.native="getInfo"
          />
        </el-col>

        <!-- 根据重要性 -->
        <el-col :span="8">
          <el-select
            v-model="listQuery.importance"
            placeholder="重要性"
            clearable
            class="filter-item"
          >
            <el-option
              v-for="item in importanceOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-col>
      </el-row>
      <el-row>
        <!-- 根据语言类型 -->
        <el-col :span="8">
          <el-select
            v-model="listQuery.type"
            placeholder="类型"
            clearable
            class="filter-item"
          >
            <el-option
              v-for="item in typeOptions"
              :key="item.key"
              :label="item.display_name+'('+item.key+')'"
              :value="item.key"
            />
          </el-select>
        </el-col>
        <!-- 排列顺序 -->
        <el-col :span="8">
          <el-select
            v-model="listQuery.sort"
            class="filter-item"
            @change="getInfo"
          >
            <el-option
              v-for="item in sortOptions"
              :key="item.key"
              :label="item.label"
              :value="item.key"
            />
          </el-select>
        </el-col>
      </el-row>

      <el-row type="flex" justify="end">
        <el-col :span="8">
          <el-button
            v-waves
            class="filter-item"
            type="primary"
            icon="el-icon-search"
            @click="getInfo"
          >
            查询
          </el-button>
          <el-button
            v-waves
            class="filter-item"
            type="primary"
            icon="el-icon-refresh"
            @click="reset"
          >
            重置
          </el-button>

        </el-col>
      </el-row>
    </div>

    <hr style="border:none;background:#e0e0e0;height:1px;">

    <!-- 添加信息 -->
    <el-row type="flex" justify="end">
      <el-col :span="1">
        <el-button
          type="primary"

          class="buttonMargin"
          @click="createInfo"
        >
          添加
        </el-button>
      </el-col>
    </el-row>
    <!-- 表格区 -->
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      class="editTableStyle"
      @sort-change="sortChange"
    >
      <!-- id -->
      <el-table-column
        label="序号"
        prop="id"
        sortable="custom"
        align="center"
        width="90"
      >
        <template slot-scope="scope">
          <span>\{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <!-- 可选时间 -->
      <el-table-column
        label="时间"
        width="250"
        align="center"
      >
        <template slot-scope="scope">
          <el-date-picker
            v-if="scope.row.edit"
            v-model="scope.row.timestamp"
            type="datetime"
          />
          <span v-else>\{{ scope.row.timestamp |parseTime() }}</span>
        </template>
      </el-table-column>
      <!-- 可改标题和类型 -->
      <el-table-column
        label="标题"
        class="titleStyle"
        min-width="150px"
      >
        <template slot-scope="{row}">
          <template v-if="row.edit">
            <el-input
              v-model="row.title"
              class="inputStyle"
            />
            <el-select
              v-model="row.type"
              class="selectStyle"
            >
              <el-option
                v-for="item in typeOptions"
                :key="item.key"
                :label="item.display_name"
                :value="item.key"
              />
            </el-select>
          </template>
          <template v-else>
            <span>\{{ row.title }}</span>
            <el-tag>\{{ row.type | typeFilter }}</el-tag>
          </template>

        </template>
      </el-table-column>
      <!-- 作者 -->
      <el-table-column
        label="作者"
        min-width="30px"
        align="center"
      >
        <template slot-scope="scope">
          <span>\{{ scope.row.author }}</span>
        </template>
      </el-table-column>

      <!-- 可选重要性 -->
      <el-table-column
        label="重要性"
        width="100px"
        align="center"
      >
        <template slot-scope="scope">
          <el-rate
            v-if="scope.row.edit"
            v-model="scope.row.importance"
            :colors="['#99A9BF', '#F7BA2A', '#ff5050']"
            :max="3"
          />

          <svg-icon
            v-for="n in +scope.row.importance"
            v-else
            :key="n"
            icon-class="star"
            class="meta-item__icon"
            style="color:#ff5050"
          />
        </template>
      </el-table-column>

      <!-- 阅读量 -->
      <el-table-column
        label="阅读数"
        align="center"
        width="95"
      >
        <template slot-scope="{row}">
          <span v-if="row.pageviews">\{{ row.pageviews }}</span>
          <span v-else>0</span>
        </template>
      </el-table-column>

      <!-- 审核人 -->
      <el-table-column
        label="审核人"
        width="110px"
        align="center"
      >
        <template slot-scope="scope">
          <span>\{{ scope.row.reviewer }}</span>
        </template>
      </el-table-column>

      <!-- 操作 -->
      <el-table-column
        label="操作"
        align="center"
        width="230"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{row}">
          <!-- 编辑信息 -->
          <el-button
            v-if="row.edit"
            type="success"

            @click="confirm(row)"
          >
            确 定
          </el-button>
          <el-button
            v-else
            type="primary"

            @click="edit(row)"
          >
            编辑
          </el-button>

          <!-- 取消添加 -->
          <el-button
            v-if="row.cancelAdd"

            type="danger"
            @click="cancelAdd"
          >
            取 消
          </el-button>
          <!-- 删除信息 -->
          <el-button
            v-else

            type="danger"
            @click="deletedInfo(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { fetchList, updateArticle } from '@/api/article_table{{timestamp}}'
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'
import { UdNotice } from 'udesk-vue'

// 语言类型数组
const typeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// 遍历数组，将数据以 CN：China 的格式存储在对象中
const typeObject = typeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'InlineTable',
  components: { Pagination },
  directives: { waves },
  filters: {
    typeFilter(type) {
      return typeObject[type]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        importance: undefined,
        title: undefined,
        type: undefined,
        sort: '+id'
      },
      importanceOptions: [1, 2, 3],
      typeOptions,
      sortOptions: [
        { label: 'ID Ascending', key: '+id' },
        { label: 'ID Descending', key: '-id' }
      ],

      showReviewer: false,
      temp: {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        type: '',
        edit: false,
        cancelAdd: false
      },

      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.items
        this.total = response.data.total
        setTimeout(() => {
          this.listLoading = false
        }, 1500)
      })
    },
    getInfo() {
      this.listQuery.page = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.getInfo()
    },
    edit(row) {
      row.edit = !row.edit
    },
    reset() {
      this.listQuery = {
        page: 1,
        limit: 20,
        importance: undefined,
        title: undefined,
        type: undefined,
        sort: '+id'
      }
    },
    resetTemp() {
      this.temp = {
        id: this.total + 1,
        author: 'vue-element-admin',
        reviewer: '未审核',
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        type: '',
        edit: true,
        cancelAdd: true
      }
    },
    createInfo() {
      this.resetTemp()
      this.list.unshift(this.temp)
    },
    cancelAdd() {
      this.list.splice(0, 1)
    },
    confirm(row) {
      if (row.timestamp !== '' && row.title !== '' && row.type !== '') {
        row.edit = false
        row.cancelAdd = false
        const tempData = Object.assign({}, row)
        tempData.timestamp = +new Date(tempData.timestamp)
        updateArticle(tempData).then(() => {
          for (const v of this.list) {
            if (v.id === row.id) {
              const index = this.list.indexOf(v)
              this.list.splice(index, 1, row)
              break
            }
          }
          UdNotice({
            noticeType: 'message',
            title: '成功',
            type: 'success',
            message: '更新成功',
            dangerouslyUseHTMLString: true,
            duration: 5000
          })
        })
      } else {
        UdNotice({
          noticeType: 'message',
          title: '失败',
          type: 'fail',
          message: '添加失败，不能未选项',
          dangerouslyUseHTMLString: true,
          duration: 5000
        })
      }
    },

    deletedInfo(row) {
      UdNotice({
        noticeType: 'message',
        title: '成功',
        type: 'success',
        message: '删除成功',
        dangerouslyUseHTMLString: true,
        duration: 5000
      })

      const index = this.list.indexOf(row)
      this.list.splice(index, 1)
    },
    parseTime(time, cFormat) {
      if (arguments.length === 0) {
        return null
      }
      const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
      let date
      if (typeof time === 'object') {
        date = time
      } else {
        if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
          time = parseInt(time)
        }
        if ((typeof time === 'number') && (time.toString().length === 10)) {
          time = time * 1000
        }
        date = new Date(time)
      }
      const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
      }
      const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key]
        if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
        if (result.length > 0 && value < 10) {
          value = '0' + value
        }
        return value || 0
      })
      return time_str
    }
  }
}
</script>
<style lang="scss" scoped>
    .filter-container{
        .el-row{
            .el-col{
                display:flex;
                justify-content: flex-end;
                align-items: center;

                .el-input,.el-select{
                    width:90%;
                }
            }
        }
    }

            .inputStyle{
                width:80%;
            }
            .selectStyle{
                width: 15%;
                input{
                    height: 32px;
                    line-height: 32px;
                }
            }
    .buttonMargin{
      margin-bottom:10px
    }
</style>

